import React, {useMemo} from 'react'
import {Link} from "react-router-dom";
import {PostAuthor} from "../users/postAuthor";
import {TimeAgo} from "./TimeAgo";
import {ReactionButtons} from "./ReactionButtons";
import {Spinner} from "../../components/Spinner";
import {useGetPostsQuery} from "../api/apiSlice";
import classnames from "classnames";

let PostExcerpt = ({ post }) => {
  // const post = useSelector(state => selectPostById(state, postId))

  return (
    <article className="post-excerpt" key={post.id}>
      <h3>{post.title}</h3>
      <div>
        <PostAuthor userId={post.user}></PostAuthor>
        <TimeAgo timestamp={post.date}></TimeAgo>
      </div>
      <p className="post-content">{ post.content.substring(0, 100) }</p>
      <ReactionButtons post={post} />
      <Link to={`/posts/${post.id}`} className="button muted-button">
        View Post
      </Link>
    </article>
  )
}

// PostExcerpt = React.memo(PostExcerpt) // React.memo：确保组件只有在props真正更改时才会重新渲染

export const PostsList = () => {
  // const posts = useSelector(state => state.posts)
  // const posts = useSelector(selectAllPosts)

  // 根据日期对文章进行排序
  // const orderedPosts = posts.slice().sort((a, b) => {
  //   return b.date.localeCompare(a.date)
  // })

  // const dispatch = useDispatch()
  //
  // const postStatus = useSelector(state => state.posts.status)
  // const error = useSelector(state => state.posts.error)
  //
  // useEffect(() => {
  //   if (postStatus === 'idle') {
  //     dispatch(fetchPosts())
  //   }
  // }, [postStatus, dispatch])

  const {
    data: posts = [], // 当data没有返回时给posts默认一个空数组，这样我们对posts进行排序时就不会报错
    isLoading,
    isFetching,
    isSuccess,
    isError,
    error,
    refetch
  } = useGetPostsQuery()

  const sortedPosts = useMemo(() => {
    const sortedPosts = posts.slice()
    sortedPosts.sort((a, b) => b.date.localeCompare(a.date))

    return sortedPosts
  }, [posts])

  let content

  if (isLoading) {
    // 加载中
    content = <Spinner text="Loading..."></Spinner>
  } else if (isSuccess) {
    // 加载完成渲染数据
    const renderedPosts = sortedPosts.map(post => (
      <PostExcerpt key={post.id} post={post} />
    ))

    const containerClassname = classnames('posts-container', {
      disabled: isFetching
    })

    content = <div className={containerClassname}>{renderedPosts}</div>
    // content = sortedPosts.map(post => <PostExcerpt key={post.id} post={post} />)
  } else if (isError) {
    // 提示错误
    content = <div>{error.toString()}</div>
  }

  // if (postStatus === 'loading') {
  //   content = <Spinner text="Loading..."></Spinner>
  // } else if (postStatus === 'succeeded') {
  //   const orderedPosts = posts.slice()
  //                             .sort((a, b) => b.date.localeCompare(a.date))
  //
  //   content = orderedPosts.map(post => {
  //     // console.log(post)
  //     return (
  //       <PostExcerpt key={post.id} postId={post.id}></PostExcerpt>
  //     )
  //   })
  // } else if (postStatus === 'failed') {
  //   content = <div>{error}</div>
  // }

  // const renderedPosts = orderedPosts.map(post => (
  //   <article className="post-excerpt" key={post.id}>
  //     <h3>{post.title}</h3>
  //     <div>
  //       <PostAuthor userId={post.user}></PostAuthor>
  //       <TimeAgo timestamp={post.date}></TimeAgo>
  //     </div>
  //     <p className="post-content">{post.content.substring(0, 100)}</p>
  //     <PostAuthor userId={post.userId}></PostAuthor>
  //     <ReactionButtons post={post}></ReactionButtons>
  //     <Link to={`/posts/${post.id}`} className="button muted-button">
  //       View Post
  //     </Link>
  //   </article>
  // ))


  return (
    <section className="posts-list">
      <h2>Posts</h2>
      <button onClick={refetch}>Refetch Posts</button>
      {content}
    </section>
  )
}
